package com.speechb.common.text;

import com.hankcs.hanlp.HanLP;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author : llj
 * @version :2.1.0
 * @date : 2019/8/10 10:54
 */


public class TextUtil {
    public static void main(String [] args) {
        System.out.println(getUUID());
    }
    private static final String RESOUCE_URL = "https://tv.speechb.com";
    /**
     * 获取UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
    public static String getEncryptedCode(String content, String salt) {
        return  ConfigEncryptUtils.encrypt(content, salt);
    }

    final static Pattern imagePattern = Pattern.compile("<img.*?src=[\\\"|'](.*?)[\\\"|'].*?>");
    final static Pattern imgSrcPattern = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
    final static Pattern pSrc = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");

    /**
     * 判断字符是否为空，为空返回true
     *
     * @param value
     * @return
     */
    public static boolean isEmpty(String value) {
        if (value == null || value.length() == 0) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符数组是否为空，有一个空则返回true
     *
     * @param values
     * @return
     */
    public static boolean isEmptys(String... values) {
        for (int i = 0; i < values.length; i++) {
            if (isEmpty(values[i])) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断字符数组是否为空，有一个空则返回true
     *
     * @param values
     * @return
     */
    public static boolean isEmptys(Object... values) {
        for (int i = 0; i < values.length; i++) {
            if (isEmpty(values[i])) {
                return true;
            }
        }
        return false;
    }

    public static boolean isEmpty(Object value) {
        if (value == null || "".equals(value)) {
            return true;
        }
        return false;
    }

    /**
     * 得到网页中图片的地址
     * 取最大的图片路径数maxSize
     */
    public static List<String> getImgStr(String htmlStr, int maxSize) {
        if (StringUtils.isEmpty(htmlStr)) {
            System.out.println("[getImgStr]htmlStr is empty");
            return Collections.emptyList();
        }
        List<String> set = new ArrayList<String>();
        Matcher matcher = imagePattern.matcher(htmlStr);
        int i = 0;
        while (matcher.find() && i < maxSize) {
            set.add(getImgSrc(matcher.group()));
            i++;
        }

        return set;
    }

    /**
     * 获取img标签中的src值
     *
     * @param content
     * @return
     */
    public static String getImgSrc(String content) {
        String str_src = null;
        //目前img标签标示有3种表达式
        //<img alt="" src="1.jpg"/>   <img alt="" src="1.jpg"></img>     <img alt="" src="1.jpg">
        //开始匹配content中的<img />标签
        Matcher m_img = imgSrcPattern.matcher(content);
        boolean result_img = m_img.find();
        if (result_img) {
            while (result_img) {
                //获取到匹配的<img />标签中的内容
                String str_img = m_img.group(2);

                //开始匹配<img />标签中的src
                Matcher m_src = pSrc.matcher(str_img);
                if (m_src.find()) {
                    str_src = m_src.group(3);
                }
                //结束匹配<img />标签中的src

                //匹配content中是否存在下一个<img />标签，有则继续以上步骤匹配<img />标签中的src
                result_img = m_img.find();
            }
        }
        return str_src;
    }

    /**
     * 替换字符串里最后出现的元素
     * 调用这个方法
     * String st = "test CS1.6 + CS1.6 + CS1.6 = CS1.6 test";
     * System.out.println( replaceLast( st, "CS1.6", "CSGO" ) );
     * 输出 test CS1.6 + CS1.6 + CS1.6 = CSGO test
     *
     * @param text 字符串
     * @param strToReplace 需要替换的字符串
     * @param replaceWithThis 替换成的字符串
     * @return 替换完成的字符串
     */
    public static String replaceLast( String text, String strToReplace,
                                      String replaceWithThis ) {
        if (StringUtils.isEmpty(text)) {
            return "";
        }
        return text.replaceFirst( "(?s)" + strToReplace + "(?!.*?" + strToReplace
                + ")", replaceWithThis );
    }

    public static String getVipActivationCode() {
        return RandomStringUtils.random(12, "1234567890");
    }

    /**
     * 获得字符串中文
     * @param content
     * @return
     */
    public static String getChinese(String content) {
        if (StringUtils.isEmpty(content)) {
            return "";
        }
        return content.replaceAll("[^\\u4e00-\\u9fa5]", "");
    }

    /**
     * @param targetStr 要处理的字符串
     * @description 切割字符串，将文本和img标签碎片化，如"ab<img>cd"转换为"ab"、"<img>"、"cd"
     */
    public static List<String> cutStringByImgTag(String targetStr) {
        List<String> splitTextList = new ArrayList<String>();
        Pattern pattern = Pattern.compile("<img.*?src=[\\\"|'](.*?)[\\\"|'].*?>");
        Matcher matcher = pattern.matcher(targetStr);
        int lastIndex = 0;
        while (matcher.find()) {
            if (matcher.start() > lastIndex) {
                splitTextList.add(targetStr.substring(lastIndex, matcher.start()));
            }
            splitTextList.add(targetStr.substring(matcher.start(), matcher.end()));
            lastIndex = matcher.end();
        }
        if (lastIndex != targetStr.length()) {
            splitTextList.add(targetStr.substring(lastIndex, targetStr.length()));
        }
        return splitTextList;
    }

    public static String convertArticleContent(String articleContent) {
        if (StringUtils.isEmpty(articleContent)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        List<String> splitImgList = TextUtil.cutStringByImgTag(articleContent);
        for (String text : splitImgList) {
            if (text.contains("<img") && text.contains("src=")) {
                //imagePath可能是本地路径，也可能是网络地址
                String imagePath = TextUtil.getImgSrc(text);
                if (StringUtils.isEmpty(imagePath)) {
                     continue;
                }
                // <img src="static/article/imgs/2018/11/13/meixueyuan/131430dv4e4kpmi4fw7bk7.png">
                sb.append("<img ");
                sb.append("class='img-responsive'");
                sb.append(" src='");
                if (!(imagePath.startsWith("http://") || imagePath.startsWith("https://"))) {
                    sb.append(RESOUCE_URL);
                    sb.append('/');
                }
                sb.append(imagePath);
                sb.append("'>");
            } else {
                sb.append(text);
            }
        }
        return sb.toString();
    }

    public static String covertWholeUrl(String partUrl) {
        if (StringUtils.isEmpty(partUrl)) {
            return "";
        }
        if (!(partUrl.startsWith("http://") || partUrl.startsWith("https://"))) {
            StringBuilder sb = new StringBuilder();
           return sb.append(RESOUCE_URL).append('/').append(partUrl).toString();
        }
        return partUrl;
    }

    // 去除图片域名
    public static String removeImgDomain(String articleContent) {
        if (StringUtils.isEmpty(articleContent)) {
            return "";
        }
        StringBuilder sb = new StringBuilder(articleContent.length());
        List<String> splitImgList = TextUtil.cutStringByImgTag(articleContent);
        String imagePath;
        for (String text : splitImgList) {
            if (text.contains("<img") && text.contains("src=")) {
                //imagePath可能是本地路径，也可能是网络地址
                imagePath = TextUtil.getImgSrc(text);
                if (StringUtils.isEmpty(imagePath)) {
                    continue;
                }
                // <img src="static/article/imgs/2018/11/13/meixueyuan/131430dv4e4kpmi4fw7bk7.png">
                if (imagePath.startsWith("http://") || imagePath.startsWith("https://")) {
                    text = text.replaceFirst(imagePath,imagePath.replaceFirst("[\\w]+:\\/\\/([^\\/]+)/", ""));
                }
                sb.append(text);
            } else {
                sb.append(text);
            }
        }
        return sb.toString();
    }

    /**
     * 获取摘要
     * @return 返回摘要
     */
    public static String getSummary(String document, int maxLength) {
        if (StringUtils.isEmpty(document)) {
            return "";
        }
        String clean = Jsoup.clean(document, new Whitelist());
        if (StringUtils.isEmpty(clean)) {
            return "";
        }
        return HanLP.getSummary(clean, maxLength);
    }

    public static List<String> getTotalImgUrlList(List<String> imgUrlList) {
        if (CollectionUtils.isEmpty(imgUrlList)) {
            return Collections.emptyList();
        }
        List<String> totalUrlList = new ArrayList<>(imgUrlList.size());
        for (String s : imgUrlList) {
            totalUrlList.add(getTotalImgUrl(s));
        }
        return totalUrlList;
    }
    public static String getTotalImgUrl(String url) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(url)) {
            return "";
        }
        if (url.startsWith("https://") || url.startsWith("http://")) {
            return url;
        }
        return "https://tv.speechb.com/"+ url;
    }
}
